package com.vaha.presentation.rest;

import com.cyber.application.controller.AuthingTokenController;
import com.cyber.domain.constant.HttpResultCode;
import com.cyber.domain.entity.DataResponse;
import com.cyber.domain.entity.IdRequest;
import com.cyber.domain.entity.PagingData;
import com.cyber.domain.entity.Response;
import com.vaha.application.service.UserAccountService;
import com.vaha.domain.entity.UserAccount;
import com.vaha.domain.request.CreateUserAccountRequest;
import com.vaha.domain.request.UpdateUserAccountRequest;
import com.vaha.domain.request.UserAccountRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

@RestController
@RequiredArgsConstructor
public class UserAccountRest extends AuthingTokenController {

	private final UserAccountService userAccountService;

	@GetMapping("/useraccount/search")
	public Response searchUserAccount(@Valid UserAccountRequest request) {
		DataResponse<PagingData<UserAccount>> response = new DataResponse<>();
        UserAccount  useraccount = request.toEvent(getTenantCode());
		PagingData<UserAccount> userAccountPage = userAccountService.selectPage(useraccount);
		response.setData(userAccountPage);
		return response;
	}


	@GetMapping("/useraccount")
	public Response selectOneUserAccount(@Valid IdRequest idRequest) {
		DataResponse<UserAccount> response = new DataResponse<>();

		UserAccount userAccount = new UserAccount();
		userAccount.setId(idRequest.getId());
        userAccount.setTenantCode(getTenantCode());
		userAccount = userAccountService.selectOne(userAccount);

		response.setData(userAccount);
		return response;
	}

	@PostMapping("/useraccount")
	public Response saveUserAccount(@RequestBody @Valid CreateUserAccountRequest request) {
	    UserAccount  useraccount = request.toEvent(getSessionId(),getTenantCode());

		int result = userAccountService.save(useraccount);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@PutMapping("/useraccount")
	public Response updateUserAccount(@RequestBody @Valid UpdateUserAccountRequest request) {
	    UserAccount  useraccount = request.toEvent(getSessionId(),getTenantCode());
		int result = userAccountService.updateById(useraccount);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@DeleteMapping("/useraccount")
	public Response deleteUserAccount(@Valid IdRequest idRequest) {
		UserAccount userAccount = new UserAccount();
		userAccount.setId(idRequest.getId());

		userAccount.setTenantCode(getTenantCode());
		userAccount.setUpdator(getSessionId());
        userAccount.setUpdateTime(new Date());

		int result = userAccountService.deleteById(userAccount);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}
}
